package com.itbaizhan.ruiji.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itbaizhan.ruiji.common.Result;
import com.itbaizhan.ruiji.utils.BaseContext;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter(filterName = "loginCheckoutFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckoutFilter implements Filter {
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        Boolean check = check(urls, request.getRequestURI());
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            Long empid =(long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empid);
            return;
        }

        if (request.getSession().getAttribute("user")!=null){
            filterChain.doFilter(request,response);
            Long userid =(long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);
            return;
        }

        // 使用Jackson ObjectMapper来序列化Result对象
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(Result.error("NOTLOGIN")));
    }

    public Boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }

}
